var express = require('express')
var router = express.Router()
const Jwt = require('jsonwebtoken')
const config = require('../config')
const { exec, getAll, getOne } = require('../db')

// 登录请求
router.post('/', async (req, res) => {
  const { username, password } = req.body
  let sql = `select *,count(*) total from blog_user where username = '${username}'`
  const data = await getOne(sql)
  if (data.total) {
    if (data.password == password) {
      let payload = {
        id: data.id,
        username: data.username,
      }
      let secretKey = config.token.secretKey
      let token = Jwt.sign(payload, secretKey, config.token.options)
      res.send({
        code: 0,
        message: '登录成功',
        token: token,
      })
    } else {
      res.send({
        code: 404,
        message: '请检查您的用户名和密码',
        token: '',
      })
    }
  } else {
    res.send({
      code: 404,
      message: '该用户名不存在',
    })
  }
})

module.exports = router
